import dayjs from 'dayjs'
import { ref } from 'vue'
import useComp from './useComp'
import useLog from './useLog'
import useProj from './useProj'
import useTeam from './useTeam'

export default () => {
  const records = ref<RecordModel[]>([])
  const recordDbs = ref<RecordDbModel[]>([])

  const { find, log } = useLog()
  const { all: allProj, find: findProj, add: addProj, projs, proj } = useProj()
  const { all: allComp, find: findComp, add: addComp, comps, comp } = useComp()
  const { all: allTeam, find: findTeam, add: addTeam, teams, team } = useTeam()

  const read = async (id: number) => {
    records.value = []
    await find(id)

    const { date: logDate, content } = log.value!
    const date = dayjs(logDate).format('YYYY-M-D')

    const reg = content
      .replace(/\s/g, '')
      .matchAll(
        /（\d{1,2}）(.{0,30}工程).{0,10}，(\D{2,4})，?([SZ]\d{3,4}).{0,10}负责人(.{2,4})[,，]/gi
      )

    for (const r of reg) {
      const [_, projName, compName, teamName, fzrName] = r

      await allProj()
      await allComp()
      await allTeam()

      const p = projs.value.find((p) => p.name.includes(projName))

      const projId = p
        ? p.id
        : await addProj({ company: '线一', name: projName, shortName: projName, dianya: '220kV' })
      await findProj(projId!)

      const c = comps.value.find((c) => c.name.includes(compName))
      const compId = c
        ? c.id
        : await addComp({ name: compName, shortName: compName, fr: '--', sjfzr: '--' })
      await findComp(compId!)

      const t = teams.value.find((t) => t.name === teamName)
      const teamId = t
        ? t.id
        : await addTeam({ name: teamName, fzr: fzrName, compId: compId!, evaluate: 0 })
      await findTeam(teamId!)

      records.value.push({
        date,
        proj: proj.value!,
        comp: comp.value!,
        team: team.value!,
        isDb: false
      })
    }
  }

  const all = async (args: Record<string, any> = {}) => {
    if (args.teamId) {
      const teamId = args.teamId
      recordDbs.value = await window.api.sql(
        `select * from records where teamId=@teamId order by date desc`,
        'findAll',
        { teamId }
      )
    } else {
      recordDbs.value = await window.api.sql(`select * from records order by date desc`, 'findAll')
    }
  }

  const add = async (data: RecordModel) => {
    return await window.api.sql<number>(
      `insert into records (projId,compId,teamId,date,created_at) values (@projId,@compId,@teamId,@date,datetime())`,
      'insert',
      {
        projId: data.proj.id,
        compId: data.comp.id,
        teamId: data.team.id,
        date: data.date
      }
    )
  }

  const del = async (id: number) => {
    return await window.api.sql(`delete from records where id=@id`, 'del', { id })
  }

  return { all, read, add, del, recordDbs, records }
}
